package com.cunshe.web.manage;

import com.cunshe.common.FileUtil;
import com.cunshe.common.ResponseVO;
import com.cunshe.common.WebConsts;
import com.cunshe.config.annotation.Login;
import com.cunshe.web.BaseController;
import com.sunkee.commons.utils.DateUtils;
import com.sunkee.commons.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.system.ApplicationHome;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.StringJoiner;

/**
 * 文件上传
 * @author xiao
 */
@Api(tags = "文件上传")
@Login
@RestController
public class FileUploadController extends BaseController {

    private Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 文件上传
     * @param file 文件流
     * @return
     */
    @ApiOperation(value = "文件上传")
    @PostMapping(value = "upload")
    public ResponseVO upload(@RequestParam MultipartFile file) {
        ApplicationHome h = new ApplicationHome(FileUploadController.class.getClass());
        File root = h.getDir();

        String prefix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        String dir = WebConsts.UPLOAD_DIRECTORY + DateUtils.getCurrentDateForInt();
        String filename = StringUtils.generateShortUuid() + prefix;
        File newFile = new File(root.getParent() + dir, filename);
        if(!newFile.exists()){
            newFile.mkdirs();
        }

        try {
            file.transferTo(newFile);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseVO.error(1, e.getMessage());
        }

        return ResponseVO.success(dir + "/" + filename);
    }

    /** 文件删除 */
    @ApiOperation(value = "文件删除")
    @PostMapping(value = "fileDelete")
    public ResponseVO fileDelete(@RequestParam("filePath") String filePath) {
        FileUtil.deleteFile(filePath);
        return ResponseVO.success();
    }

}
